#!/bin/bash

apache=/web/apache
kyoconf=$apache/conf/kyo
srvip=3.3.3.9

myexit() {
    echo ${1-exit}
    exit ${2-0}
}

isRun() {
    apache_bin='/usr/sbin/apache'
    test ! -z "$1" && apache_bin='/web/apache'
    test "x$1" = "xnginx" && apache_bin=$1
    run=$(ps -aux | grep $apache_bin 2> /dev/null | grep -v 'grep')
    test -z "$run" && echo "close"
}

apt() {
    sudo service apache2 ${1-restart}
}

code() {
    if test "x$1" == "xstatus"; then
        test "$(isRun code)" = "close"                  \
            && echo "/web/apache is not Running...!"    \
            || echo "/web/apache is Running...!"
    else
        sudo $apache/bin/apachectl ${1-restart}
    fi
}

php() {
    test $(isRun) != "close" && apt stop
    conf=php${1-7}.conf
    cd $kyoconf
    rm php.conf -f
    ln -s $conf php.conf
    code
}

vhost() {

    test $UID -ne 0 && myexit "请使用sudo运行!" 1

    grep " php.com" /etc/hosts &> /dev/null \
            || echo "$srvip php.com" >> /etc/hosts

    path=${1-/kyo}

cat > $kyoconf/vhost.conf << EOF
<VirtualHost *:80>
    ServerName php.com
    DocumentRoot "$path"
    <Directory "$path">
        DirectoryIndex index.php index.html
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
    ErrorLog "logs/php_error_log"
    CustomLog "logs/php_access_log" common
</VirtualHost>
EOF
    code
}

# ./apache apt
# ./apache
# ./apache restart
# ./apache status
# ./apache stop
# ./apache start
# ./apache 5
# ./apache 7
# ./apache path

srvop() {
    if test "x$1" = "xapt"; then
        test "$(isRun code)" != "close" && code stop
        apt
    elif test -z $1; then
        test "$(isRun)" != "close" && apt stop
        test "$(isRun code)" = "close" && code start || code
    elif test -d $1; then
        test "x$1" = "x." && vhost $(pwd) || vhost $1
    else
        test "$(isRun)" = "close" && srvname="code"
        ${srvname-apt} $1
    fi
}

test "$(isRun nginx)" != "close" && sudo /web/bin/lnmp stop

echo $1 | egrep '[0-9]' &> /dev/null && php $1 || srvop $1

